package com.example.redistest.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * redis 哨兵模式 测试
 */
@RestController
public class RedisTestController {

    private static Logger logger = LoggerFactory.getLogger(RedisTestController.class);

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 测试节点挂了哨兵重新选举新的master节点，客户端是否能动态感知到
     * 新的master选举出来后，哨兵会把消息发布出去，客户端实际上是实现了一个消息监听机制，
     * 当哨兵把新master的消息发布出去，客户端会立马感知到新master的信息，从而动态切换访问的masterip
     */

    @GetMapping("sentinel")
    public void testSentinel() {
        int i = 1;
        while (true) {
            stringRedisTemplate.opsForValue().set("zjq" + String.valueOf(i), String.valueOf(i));
            System.out.println("设置key：" + "zjq" + i);
            i++;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                logger.error("错误：", e);
            }
        }
    }
}
